<?php
require_once 'base.php';
checkAuth();

$op = Utility::getParam('op', 'query');
switch($op) {
	case 'query':
		$op();
		break;
	case 'doQuery':
		$op();
		break;
	case 'add':
		$op();
		break;
	case 'doAdd':
		$op();
		break;
	case 'modify':
		$op();
		break;
	case 'doModify':
		$op();
		break;
	default:
		echoAjax(Constants::$ERR_MISSING_PARAMS);
		break;
}

function query(){
	
	$warehouse = $GLOBALS['conf']['warehouse'];
	$userInfo = $GLOBALS['userInfo'];
	
	include $GLOBALS['ROOT_PATH'] . '/views/admin/inventory_query.phtml';
}

function doQuery() {
	
	$type = Utility::getParam('type', '');
    if (empty($type)){
    	echoAjax(Constants::$ERR_MISSING_PARAMS);
    	return ;
    }
    
    $res = Constants::$ERR_SUCCESS;
    $data = ObjectFinder::get('Cartridge')->queryByType($type, 0, 100);
    $res['type'] = isset($data[0]) ? $data[0]['id'] : '';
    $res['data'] = isset($data[0]) ? json_decode($data[0]['inventory']) : '';
    echoAjax($res);
}

function add() {
	
	$warehouse = $GLOBALS['conf']['warehouse'];
	
	include $GLOBALS['ROOT_PATH'] . '/views/admin/inventory_add.phtml';
}

function doAdd() {
	
	$type = Utility::getParam('type', '');
    foreach($_POST as $id=>$name) {
		if (is_numeric($id)) {
			$inventory[$id] = $name;
		}
	}
    if (empty($type) || empty($inventory) || !is_array($inventory)){
    	echoAjax(Constants::$ERR_MISSING_PARAMS);
    	return ;
    }
    $res = ObjectFinder::get('Cartridge')->add(array('type' => $type, 'inventory' => json_encode($inventory)));
    echoAjax($res ? Constants::$ERR_SUCCESS : Constants::$ERR_FAILED);
}

function modify() {
	
	$typeID = max(0, (int)Utility::getParam('type_id', 0));
    if (empty($typeID) || $typeID < 0) {
    	echoAjax(Constants::$ERR_INVALID_PARAMS);
    	return;
    }
    $res = ObjectFinder::get('Cartridge')->getById($typeID);
    $tmp = (array)json_decode($res[0]['inventory']);
    foreach($tmp as $key => $value) {
    	$inventory[(int)$key] = $value;
    }
    $info = isset($res[0]) ? array('id'=>$res[0]['id'], 'type'=>$res[0]['type'], 'inventory' => $inventory) : '';
	$warehouse = $GLOBALS['conf']['warehouse'];
    
	include $GLOBALS['ROOT_PATH'] . '/views/admin/inventory_modify.phtml';
}

function doModify() {
	
	$typeID = max(0, (int)Utility::getParam('type_id', 0));
    foreach($_POST as $id=>$name) {
		if (is_numeric($id)) {
			$inventory[$id] = $name;
		}
	}
    if (empty($typeID) || empty($inventory) || !is_array($inventory)){
    	echoAjax(Constants::$ERR_MISSING_PARAMS);
    	return ;
    }
    ObjectFinder::get('Cartridge')->modifyById(json_encode($inventory), $typeID);
    echoAjax(Constants::$ERR_SUCCESS);
}
?>